package com.groot.medical.servlet;

import java.io.IOException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.groot.common.controller.BaseServletController;
import com.groot.common.util.SimpleDateUtil;
import com.groot.common.util.TicketUtil;
import com.groot.medical.entity.ChronicDisease;
import com.groot.medical.entity.ChronicPattern;
import com.groot.medical.entity.Menu;
import com.groot.medical.entity.PageBean;
import com.groot.medical.entity.PersonalFiles;
import com.groot.medical.service.ChronicPatternService;
import com.groot.medical.service.ChronicPatternServiceImpl;
import com.groot.medical.service.ChronicService;
import com.groot.medical.service.ChronicServiceImpl;

@WebServlet("/sys/pattern.do")
public class ChronicPatternController extends BaseServletController{
	private static final long serialVersionUID = 1L;
	private static Logger LOGGER = Logger.getLogger(ChronicPatternController.class);
	private ChronicPatternService chronicPatternService = new ChronicPatternServiceImpl();
	private ChronicService chroniceService = new ChronicServiceImpl();
	public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOGGER.info("this is @WebServlet(\"/index.do\").execute()");
		return null;
	}
	/**
	 * 分页查询慢性病证信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findChronicPatternInfoByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String tgId = request.getParameter("tgId");
		int pageNum = Integer.parseInt(request.getParameter("pageNum"));
		List<Menu> menus=(List<Menu>) request.getSession().getAttribute("menuList");
		List<Menu> result = new ArrayList<Menu>();
		/*根据页面传过来的id与该用户所有权限的上一级id比较
		 * 若该权限的上一级传过来的id相同则存入新集合
		 */
		for(Menu menu: menus){
			if(menu.getMenuPid().equals(tgId)){
				result.add(menu);
			}
		}
		
		Gson gson = new Gson();
		request.setAttribute("resultMenus", gson.toJson(result));
		request.setAttribute("tgId", tgId);
		int pageSize = 5;
		PageBean areaPage = chronicPatternService.findChronicPatternInfoByPage(pageNum, pageSize);
        request.setAttribute("areaPage", areaPage);
		
		
		return "/WEB-INF/page/patterns/pattern_list.jsp";
	}
	/**
	 * 打开添加页面
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String toAddChronicPatternInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setAttribute("tgId", request.getParameter("tgId"));
		//查询慢性病名称
		List<ChronicDisease> chronicInfos=chroniceService.findAllChronicInfo();
		request.setAttribute("chronicInfos", chronicInfos);
		return "/WEB-INF/page/patterns/pattern_add.jsp";
	}
	/**
	 * 根据名字模糊查询
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public void findPersonInfoByName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		System.out.println(username);
		List<PersonalFiles> psersons = chronicPatternService.findAlreadyPayPerson(username);
		System.out.println("阿鲁啊："+psersons);
		Gson gson = new Gson();
		
        String str=gson.toJson(psersons);
        System.out.println("你好啊:::"+str);
        /*response.setContentType("text/html;charset=utf-8");*/
        ServletOutputStream outputStream = response.getOutputStream();
       
        outputStream.write((str.getBytes(Charset.forName("utf-8")))); //将json数据写入流中  
        outputStream.flush(); 
        outputStream.close();	
	}
	/**
	 * 添加慢性病证信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String AddChronicPatternInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String farmingcardCode = request.getParameter("farmingcardCode");
		String idcardNumber = request.getParameter("idcardNumber");
		String illName = request.getParameter("illName");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		//处理时间
		SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		Date startdate = null;
		Date enddate = null;
		try {
			startdate = time.parse(startTime);
			enddate = time.parse(endTime);
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String chrinicCode = TicketUtil.getDefaultChronic();
		//封装数据
		ChronicPattern pattern = new ChronicPattern();
		pattern.setChronicPatternCode(chrinicCode);
		pattern.setFarmingCardCode(farmingcardCode);
		pattern.setIdCardCode(idcardNumber);
		pattern.setIllName(illName);
		pattern.setStartTime(startdate);
		pattern.setEndTime(enddate);
		//添加慢性病证信息
		chronicPatternService.AddChronicPatternInfo(pattern);
		request.setAttribute("tgId", request.getParameter("tgId"));
		
		return findChronicPatternInfoByPage(request,response);
		
	}
	/**
	 * 打开修改
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String toEditChronicPatternInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("tgId", request.getParameter("tgId"));
		/*request.setAttribute("pageNum", 1);*/
		String id =request.getParameter("id");
		//查询是产生费用
		int counts = chronicPatternService.checkIsMakePayInfo(SimpleDateUtil.currentYear(),id);
		if(counts>0){
			//产生了费用
			request.setAttribute("flag", "<script type='text/javascript'>alert('已经产生了慢病报销费用，无法修改');</script>");
			
			return findChronicPatternInfoByPage(request,response);
		}else{
			//查询慢性病证信息
			ChronicPattern pattern =chronicPatternService.findChronicInfoByChronicCode(id);
			System.out.println(pattern);
			//慢性病信息
			List<ChronicDisease> chronicInfos=chroniceService.findAllChronicInfo();
			request.setAttribute("pattern", pattern);
			request.setAttribute("chronicInfos", chronicInfos);
			return "/WEB-INF/page/patterns/pattern_edit.jsp";
		}
	}
	/**
	 * 删除慢性病证
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public void deletePatternsInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String resultString = "false";
		//检验是否产生慢性病证报销记录
		int counts = chronicPatternService.checkIsMakePayInfo(SimpleDateUtil.currentYear(),id);
		if(counts>0){
			//存在报销记录
			resultString = "false";
			response.setContentType("text/html");
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(resultString.getBytes());
	        outputStream.close();
		}else{
			//删除慢性病症
			chronicPatternService.deletePattern(id);
			resultString = "true";
			response.setContentType("text/html");
	        ServletOutputStream outputStream = response.getOutputStream();
	        outputStream.write(resultString.getBytes());
	        outputStream.close();
		}
	}
}